<template>
  <view class="container">
<!--    <uni-nav-bar left-icon="back" right-text="发表" backgroundColor="#fba007" color="white" fixed height="129rpx"
      border="false" @clickRight="submit" @clickLeft="gotoBack" /> -->
    <textarea placeholder="这一刻的想法..." class="trend-content" placeholder-class="trend-placeholder" v-model="content"
      maxlength="-1" focus="true" show-confirm-bar="false" auto-focus="true" auto-height></textarea>

    <my-upload-image :list="imageList" @updateImage="updateImage"></my-upload-image>
    <view class="bottom-box">
      <view class="position-box" @click="chooseLocation">
        <uni-icons type="location" size="23" color="black"></uni-icons>
        <view class="position-box-text">所在位置</view>
        <view class="position-box-positionText" v-if="userPosition !== false">{{userPosition}}</view>
        <uni-icons type="forward" size="17" color="#ddd"></uni-icons>
      </view>
      <view class="status-box" @click="openPopup">
        <uni-icons type="person" size="23" color="black"></uni-icons>
        <view class="status-box-text">作品状态</view>
        <view class="status-box-statusText" v-if="isPrivacy === false">公开</view>
        <view class="status-box-statusText" v-else>私密</view>
        <uni-icons type="forward" size="17" color="#ddd"></uni-icons>
      </view>
    </view>
    <uni-popup ref="popup" type="bottom" is-mask-click="true">
      <view class="popup-box">
        <view class="checkbox-box">
          <uni-data-checkbox v-model="value" :localdata="range" @change="selectTrendStatus"></uni-data-checkbox>
        </view>
      </view>
    </uni-popup>
    <view class="custom" @click="submit">
      <view>发表</view>
    </view>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  export default {
    computed: {
      ...mapState('m_user', ['token', 'userinfo'])
    },
    data() {
      return {
        // 用户选择的图片列表
        imageList: [],
        // 用户上传后的图片列表
        uploadImageList: [],
        // 用户输入的内容
        content: '',
        // 用户的定位
        userPosition: false,
        // 用户是否设置私密
        isPrivacy: false,
        // 底部弹出层内容参数
        value: 0,
        range: [{
          "value": 0,
          "text": "公开"
        }, {
          "value": 1,
          "text": "私密"
        }]
      };
    },
    methods: {
      ...mapMutations('m_trend', ['updateTrendList']),
      ...mapMutations('m_user', ['updateUserTrendList']),
      // 发表
      async submit() {
        await this.uploadWorksImagesToServer()
        const submitTime = this.getNowDate()
        const publishInfo = {
          userId: this.userinfo.userID,
          avatarUrl: this.userinfo.userAvatar,
          nickName: this.userinfo.userName,
          imageList: this.uploadImageList,
          content: this.content,
          position: this.userPosition,
          likeNum: 0,
          isLiked: false,
          isPrivacy: this.isPrivacy,
          createTime: submitTime,
        }
        console.log(publishInfo)
        // 检查 publishInfo 是否为空对象
        if (Object.values(publishInfo).every(value => value !== undefined && value !== null)) {
          // 将发表内容添加进动态列表中
          if (this.isPrivacy === false) {
            // 更新作品列表
            this.updateTrendListToServer(publishInfo)
            // 更新用户作品列表
            this.updateUserTrendListToServer(publishInfo)
          } else {
            this.updateUserTrendListToServer(publishInfo)
          }
          //返回上一个页面
          uni.navigateBack({
            delta: 1 // 返回上一个页面
          });
        } else {
          return uni.$showMsg('发表失败，请重试！')
          console.log('必填字段不能为空');
        }
      },
      // 上传作品图片到服务器中
      async uploadWorksImagesToServer() {
        const nowDate = new Date();
        const year = nowDate.getFullYear();
        const month = String(nowDate.getMonth() + 1).padStart(2, "0");
        const day = String(nowDate.getDate()).padStart(2, "0");
        const hour = String(nowDate.getHours()).padStart(2, "0");
        const minute = String(nowDate.getMinutes()).padStart(2, "0");
        const second = String(nowDate.getSeconds()).padStart(2, "0");
        const uploadTime = `${year}-${month}-${day}_${hour}-${minute}-${second}`;
      
        const userID = this.userinfo.userID;
        console.log('上传作品图片');
        try {
          for (let i = 0; i < this.imageList.length; i++) {
            const filePath = this.imageList[i];
            const res = await uni.uploadFile({
              filePath: filePath,
              name: 'image',
              url: 'https://jeoz.top:3000/api/upload/worksImages?userID=' + userID + '&uploadTime=' + uploadTime
            });
            const responseData = JSON.parse(res[1].data);
            const worksImagesUrl = responseData.message.newWorksImagesUrl;
            this.uploadImageList.push(worksImagesUrl);
          }
        } catch (err) {
          console.log('图片上传失败', err);
        }
      },
      updateImage(list) {
        console.log(list)
        this.imageList = list
      },
      // 更新作品列表
      async updateTrendListToServer(publishInfo) {
        const {
          data: res
        } = await uni.$http.post('/api/publish/works', publishInfo)
        console.log('后端返回的发表结果', res)
        if(res.meta.status !== 200) return $showMsg('发表失败')
        console.log('发表作品后返回信息',res.message)
        this.updateTrendList(res.message)
      },
      // 更新用户作品列表
      async updateUserTrendListToServer(publishInfo) {
        // 准备参数
        var token = uni.getStorageSync('token')
        const query = {
          token,
          publishInfo,
        }
        const {
          data: res
        } = await uni.$http.post('/api/update/works', query)
        console.log('后端返回的发表结果', res)
        if(res.meta.status !== 200) return $showMsg('发表失败')
        console.log('发表作品后返回信息',res.message)
        this.updateUserTrendList(res.message)
      },
      // 获取当前时间
      getNowDate() {
        const now = new Date();

        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');

        const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

        return formattedDate;
      },
      // 获取当前所在位置
      chooseLocation() {
        uni.chooseLocation({
          success: (res) => {
            const latitude = res.latitude;
            const longitude = res.longitude;
            const name = res.name;
            const address = res.address;

            if (name !== '' && address !== '') {
              const cityRegex = /.+省(.+市).+/; // 定义一个正则表达式，匹配省和市之间的内容
              const matchedCity = address.match(cityRegex)[1]; // 使用正则表达式匹配到XX市的内容
              const fullName = `${matchedCity}·${name}`; // 在名称后面添加XX市，用"·"隔开
              this.userPosition = fullName
            } else {
              this.userPosition = false
            }
            console.log(this.userPosition)
          },
          fail: (err) => {
            uni.showToast({
              title: '选择位置失败',
              icon: 'none'
            });
            console.log(err);
          }
        })
      },
      // 打开底部弹出层
      openPopup() {
        this.$refs.popup.open()
      },
      // 选择作品状态
      selectTrendStatus(e) {
        const status = e.detail.data.text
        if (status === '公开') {
          this.isPrivacy = false
        } else if (status === '私密') {
          this.isPrivacy = true
        }
        this.$refs.popup.close()
      },
      // 返回按钮返回上一页
      gotoBack() {
        uni.navigateBack({
          delta: 1 // 返回的页面数，1表示返回上一个页面
        });
      }
    },
  }
</script>

<style lang="scss">
  page {
    background: white;
    // padding: 20rpx;
  }

  .container {
    // background: white;
    // margin: 20rpx;
    padding: 0 30rpx 55rpx 30rpx;
    // border: 1px solid red;
  }

  .trend-content {
    width: calc(100% - 75rpx);
    margin: 20rpx auto 50rpx auto;
    padding: 4rpx;
    letter-spacing: 1rpx;
    margin-top: 70rpx;
  }

  .trend-placeholder {
    color: #ccc;
    font-size: 30rpx;
    letter-spacing: 1rpx;
  }

  .bottom-box {
    margin: 30rpx;

    .position-box {
      height: 90rpx;
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      // border: 1px solid red;
      border-top: 1px solid #eee;
      padding: 0 10rpx;

      .position-box-text {
        flex: 1;
        height: 90rpx;
        line-height: 90rpx;
        letter-spacing: 1rpx;
        margin-left: 20rpx;
        padding-bottom: 4rpx;
      }

      .position-box-positionText {
        width: 350rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        text-align: right;
        height: 90rpx;
        line-height: 90rpx;
        margin-right: 10rpx;
        color: gray;
        letter-spacing: 1rpx;
        font-size: 28rpx;
      }
    }

    .status-box {
      height: 90rpx;
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      // border: 1px solid red;
      border-top: 1px solid #eee;
      border-bottom: 1px solid #eee;
      padding: 0 10rpx;

      .status-box-text {
        flex: 1;
        height: 90rpx;
        line-height: 90rpx;
        letter-spacing: 1rpx;
        // border: 1px solid red;
        margin-left: 20rpx;
        padding-bottom: 4rpx;
      }

      .status-box-statusText {
        height: 90rpx;
        line-height: 90rpx;
        margin-right: 10rpx;
        color: gray;
        letter-spacing: 1rpx;
        font-size: 28rpx;
      }
    }

  }

  .popup-box {
    height: 50rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    // height: 100px;
    background: white;
    // border-radius: 15rpx;
    padding: 20px;

    .checkbox-box {
      margin-left: 43rpx;
    }
  }
  .custom {
    height: 80rpx;
    margin: 30rpx;
    border-radius: 15rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 11pt;
    font-weight: bold;
    background-color: #fba007;
    color: white;
    box-shadow: 0px 1px 2px 0.1px #ddd;
  }
</style>